#!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
	import sys
	import os
	from stat import *
	from configobj import ConfigObj
	import gobject
except:
	print ("Could not import configobj. Please install configobj")

_instances = {}
_plugins = {}
_pluginsystem_config = {}
""" holds the instances to all loaded plugins"""

class Plugin(gobject.GObject):
	capabilities = []
	options = {}
	Plugin_Name = ""
	Plugin_Author = ""	
	Plugin_Website = ""
	def __init__(self):
		gobject.GObject.__init__(self)
		self.options = {}
	def setOption(self,name,value):
		self.options[name] = value
	def getOption(self,name):
		return self.options.get(name)
	def __repr__(self):
		return '<%s %r>' % (
			self.__class__.__name__,
			self.capabilities
		)
	def loadConfig(self):
		global _pluginsystem_config
		if(self.__module__ != 'gnomeagenda.CalendarProviderBase'):
			self.initPlugin({})
	def setOptions(self,vals):
		for key in vals:
			self.options[key] = vals[key]
def load_plugins(plugins):
	print "loading plugins..."
	print plugins
	for plugin in plugins:
		try:
		#print "importing plugin: %s " % plugin
			__import__(plugin, globals(), locals(),  ['plugins'])
		except Exception, e:
			print "Could not load %s Plugin" % plugin
			print e
	pass

def init_plugin_system():
	cfg = {}
	cfg['path'] = os.path.realpath(os.path.join(os.path.dirname( __file__ ),'plugins'))
	global _pluginsystem_config
	#print "Initializing plugin system..."
	_pluginsystem_config = cfg
	plugins = []
	if not cfg['path'] in sys.path:
		sys.path.insert(0, cfg['path'])
	try:
		names = os.listdir(cfg['path'])
		for name in names:
			try:
				st = os.lstat(os.path.join(cfg['path'], name,'__init__.py'))
				if(S_ISREG(st.st_mode)):
					plugins.append(name)
			except os.error:
				continue
				print "os.error occured"
		load_plugins(plugins)
	except Exception,e:
		print "Could not read pulgins folder %s" % cfg['path']
		print e

def find_all_plugins(base = None):
	"""return all subclasses of CalendarProviderBase"""
	result = []
	if(base == None):
		base = Plugin.__subclasses__()
	#print base
	for plugin in base:
		##somehow every plugin is also in this list with module..classname
		if(("%s" % plugin).find('..')) != -1:
			continue
		result.append(plugin)
		if(plugin.__subclasses__()):
			result.extend(find_all_plugins(plugin.__subclasses__()))
	#print "Fould the following plugins: \n%s" % result
	return result

def get_by_capability(capability):
	result = []
#	print "ALL PLUGINS"
#	print find_all_plugins()
	for plugin in find_all_plugins():
		if capability in plugin.capabilities:
			#print plugin
			if not plugin in _instances:
				_instances[plugin] = plugin()
				_instances[plugin].loadConfig()
				#TODO: automatically load the preferences of this plugin
			result.append(_instances[plugin])
	return result	
	


